<template>
  <vxe-column type="radio" width="60" class="table-radio">
    <template #header>
      <span class="table-radio-head" :class="{ disabled: !selectRowValue }" @click="clearRadioRow">取消选择</span>
    </template>
    <template #radio="{ row }">
      <div style="text-align: center" @click.stop="setRadioRow(row)">
        <i v-if="checked(row)" class="vxe-icon-success-circle-fill"></i>
        <i v-else class="vxe-icon-success-circle"></i>
      </div>
    </template>
  </vxe-column>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue';
import { get } from 'lodash-es';

export default {
  name: 'table-radio',
  props: {
    modelValue: { default: undefined },
    valueField: { type: String, default: 'id' },
    VxeTableGetter: { type: Function, default: undefined },
  },
  setup(props, ctx) {
    const selectRowValue = ref(null);

    const checked = computed(() => {
      return (row) => get(row, props.valueField) === selectRowValue.value;
    });

    onMounted(() => {
      watch(
        () => props.modelValue,
        () => (selectRowValue.value = props.modelValue),
        { immediate: true }
      );
    });

    const output = () => {
      ctx.emit('update:modelValue', selectRowValue.value);
      setTimeout(() => {
        ctx.emit('change', selectRowValue.value);
      }, 0);
    };

    function getVxeTable(handle) {
      if (typeof props.VxeTableGetter === 'function') {
        const VxeTable = props.VxeTableGetter();
        if (VxeTable) {
          return handle(VxeTable, ...[].slice.apply(arguments, 1));
        } else {
          console.warn('VxeTableGetter got invalid table ref instance!');
        }
      }
    }

    const setRadioRow = (row) => {
      selectRowValue.value = get(row, props.valueField);
      getVxeTable((vxeTable, row) => vxeTable.setRadioRow(row), row);
      output();
    };

    const clearRadioRow = () => {
      selectRowValue.value = null;
      getVxeTable((vxeTable) => vxeTable.clearRadioRow());
      output();
    };

    return { selectRowValue, checked, setRadioRow, clearRadioRow };
  },
};
</script>

<style lang="less">
.table-radio {
  [class*='vxe-icon-success-circle'] {
    color: #1890ff;
    cursor: pointer;
  }
}
.table-radio-head:not(.disabled) {
  color: #1890ff;
  cursor: pointer;
}
.table-radio-head.disabled {
  color: #c0c0c0;
  cursor: not-allowed;
}
</style>
